<?php

namespace App\Services\Assess;

use App\Helpers\JwtUtils;
use App\Models\Account\UserAccountModel;
use App\Models\Assess\CommentGuideLinkModel;
use App\Models\Assess\CommentGuideLinkSkuModel;
use App\Models\Assess\CommentGuideLinkUserModel;
use App\Models\UserModel;
use App\Services\BaseService;
use App\Services\Common\CommonService;
use App\Services\Common\RedisService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 留评引导链接
 */
class CommentGuideLinkService extends BaseService
{

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new CommentGuideLinkModel();
    }

    /**
     * @Notes:获取操作相关信息
     * @Interface getCommentConfig
     * @author: wuyu
     * @Time: 2023/7/14   10:14
     */
    public function getCommentConfig()
    {
        $config = [];
        //获取用户信息
        $userData = RedisService::getUserList();
        $config['user_list'] = $userData;
        return message("操作成功", true, $config);

    }

    public function getList()
    {
        $param = request()->all();

        // 查询条件
        $map = [];
        $map[] = ["mark", '=', 1];
        // 二维码Url
        $url = getter($param, "url");
        $platformSku = getter($param, "platform_sku");
        $sort = $param['sort'] ?? 'sort';
        $order = $param['order'] ?? 'DESC';
        $page_size = getter($param, 'page', 1);
        $limit = getter($param, 'limit', 10);
        $platformSkuStr = str_replace(['；', ',', '，',"\r\n", "\r", "\n"], ';', $platformSku);
        if (!empty($platformSkuStr)) $platformSkuArr = array_unique(explode(';', $platformSkuStr));
        if ($url) {
            $map[] = ["url", 'like', "%{$url}%"];
        }

        //权限过滤 组员可以看一个组的信息
        $createUserAuth = CommonService::userAuth();

        $model2 = $this->model->where($map);
        if (!empty($createUserAuth)) $model2->whereIn('create_user',$createUserAuth);
        $count = $model2->count();
        if (!empty($createUserAuth)) $map[] = ['create_user', 'in', $createUserAuth];

        $offset = ($page_size - 1) * $limit;
        $list = $this->model->getList($map, [[$sort, $order]],"{$offset},{$limit}");

        //获取子信息
        $userIdArr = $userNameArr = [];
        if (!empty($list)) {
            $mainIds = array_column($list, 'id', 'id');
            //获取负责运营人
            $CommentGuideLinkUserModel = new CommentGuideLinkUserModel();
            $userData = $CommentGuideLinkUserModel->whereIn('guide_link_id',$mainIds)->get()->toArray();
            foreach ($userData as $v){
                $userArr[$v['guide_link_id']][] = $v['user_id'];
                $userNameArr[$v['guide_link_id']][] = $v['user_name'];
            }
        }

        if ($list) {
            foreach ($list as $key=>$val) {
                $info = $this->model->getInfo($val['id']);
                if (!$info) {
                    continue;
                }
                $info['user_ids'] = [];
                if (!empty($userArr[$val['id']])){
                    $info['user_ids'] = $userArr[$val['id']];
                    $info['user_name_html'] = implode(';',$userNameArr[$val['id']]);
                }

                if (!empty($info['url_path'])) $info['url_path'] = IMG_URL . $info['url_path'];
                if (!empty($info['amazon_comment_url_path'])) $info['amazon_comment_url_path'] = IMG_URL . $info['amazon_comment_url_path'];
                $list[$key] = $info;
            }
        }
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
    }

    public function status()
    {

        $params = request()->all();

        $id = $params['id'] ?? 0;
        $status = $params['status'] ?? 0;
        if (empty($id) || empty($status)) {
            return message("参数不存在", false, []);
        }
        $data = ['status' => $status];
        $this->model->where('id', $id)->update($data);
        $this->model->cacheReset($id, $data, $id);
        return message("操作成功", true, []);
    }

    /**
     * 添加或编辑
     * @return array
     * @since 2020/11/11
     * @author 牧羊人
     */
    public function edit()
    {
        DB::connection($this->model->connection)->beginTransaction(); //开启事务
        try {
            $params = request()->all();
            $data = [
                'url' => $params['url'] ?? '',
                'url_path' => $params['url_path'] ?? '',
                'url_ssl' => $params['url_ssl'] ?? '',
                'url_ssl_path' => $params['url_ssl_path'] ?? '',
                'amazon_comment_url' => $params['amazon_comment_url'] ?? '',
                'amazon_comment_url_path' => $params['amazon_comment_url_path'] ?? '',
                'sort' => $params['sort'] ?? 10,
            ];

            // 图片处理
            $urlPath = getter($data, "url_path");
            $amazonCommentUrlPath = getter($data, "amazon_comment_url_path");
            if (!empty($urlPath)) {
                $data['url_path'] = str_replace(IMG_URL, "", $urlPath);
            }
            if (!empty($amazonCommentUrlPath)) {
                $data['amazon_comment_url_path'] = str_replace(IMG_URL, "", $amazonCommentUrlPath);
            }
            // 开启事务
            $userId = JwtUtils::getUserId();
            $platformSku = $params['platform_sku'] ?? '';
            if (!empty($data['create_user_name'])) unset($data['create_user_name']);
            if (!empty($data['update_user_name'])) unset($data['update_user_name']);
            if (!empty($asin)) unset($data['asin']);
            if (!empty($params['id'])) {
                $id = $params['id'];
                $data['id'] = $id;
                $data['update_time'] = time();
//                $this->model->edit($data);
                $this->model->where('id', $id)->update($data);
                $this->model->cacheReset($id, $data, $id);
            } else {
                $data['create_user'] = $data['update_user'] = $userId;
                $data['create_time'] = time();
                $id = $this->model->insertGetId($data);
            }
            if (!$id) {
                throw new \Exception('保存失败');
            }

            $CommentGuideLinkUserModel = new CommentGuideLinkUserModel();
            $UserModel = new UserModel();
            $userIds = $params['user_ids'] ?? [];
            $userArr = [];
            if (!empty($userIds)){
                $userList = $UserModel->whereIn('id',$userIds)->get(['id','realname'])->toArray();
                $userArr = array_column($userList,'realname','id');
            }

            $CommentGuideLinkUserModel->where('guide_link_id', $id)->delete();
            foreach ($userIds as $vv){
                $userData = [
                    'guide_link_id'=>$id,
                    'user_id'=>$vv,
                    'user_name'=>$userArr[$vv] ?? ''
                ];
                $CommentGuideLinkUserModel->insert($userData);
            }
            DB::connection($this->model->connection)->commit(); //事务提交
            return message("保存成功", true, []);

        } catch (\Exception $e) {
            DB::connection($this->model->connection)->rollBack(); //事务回滚
            return message("保存失败:" . $e->getMessage(), false, []);
        }

    }


}
